package zonda.okhttp3post;

import android.content.Context;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import zonda.okhttp3post.gson.GsonConverterFactory;

import static zonda.okhttp3post.Constants.LOG_TAG;

/**
 * Created by Zonda on 2016/12/16.
 */

public class AppClient {

  public static void testOkHttp3Post(@NonNull Context context) {


    RequestBody requestBody1 = getRequestBody(context, "ConstraintLayout.jpg");
    RequestBody requestBody2 = getRequestBody(context, "retrofit-overview.jpg");
    MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("_uid", Constants.UID)
        .addFormDataPart("_udid", "6633300");
    if (requestBody1 != null) {
      multipartBodyBuilder.addFormDataPart("pic", "pic.jpg", requestBody1);
    }
    if (requestBody2 != null) {
      multipartBodyBuilder.addFormDataPart("pic1", "pic1.jpg", requestBody2);
    }
//      multipartBody.toString();
    MultipartBody multipartBody = multipartBodyBuilder.build();
    Request request = new Request.Builder()
        .url(Constants.TEST_UPLOADS_URL)
        .post(multipartBody)
        .build();
    OkHttpClient okHttpClient = new OkHttpClient.Builder()

        .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
      @Override
      public void onFailure(Call call, IOException e) {
        Log.i(LOG_TAG, " onFailure: " + e.toString());
      }

      @Override
      public void onResponse(Call call, Response response) throws IOException {
        String responseStr = response.body().string();
        Log.i(LOG_TAG, " onResponse: " + responseStr);
      }
    });


  }

  public static void testRetrofit2(Context context) {

    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://dis.myzaker.com/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();

    final RequestBody requestBody = getRequestBody(context, "Retrofit-ParameterHandler.png");
    if (requestBody != null) {
      MultipartBody.Part part = MultipartBody.Part.createFormData("pic", "pic.png", requestBody);
      retrofit2.Call<BaseResult> retrofitCall = retrofit.create(ClientService.class)
          .uploadImages(Constants.TEST_UPLOAD_URL, part, "99900773", Constants.UID);
      retrofitCall.enqueue(new retrofit2.Callback<BaseResult>() {
        @Override
        public void onResponse(retrofit2.Call<BaseResult> call,
                               retrofit2.Response<BaseResult> response) {
          Log.i(LOG_TAG, " onResponse getStat: " + response.body().getStat()
              + " getMsg: " + response.body().getMsg());
        }

        @Override
        public void onFailure(retrofit2.Call<BaseResult> call, Throwable t) {
          Log.i(LOG_TAG, " onFailure Throwable: " + t.getMessage());
        }
      });
    }
  }

  static RequestBody getRequestBody(Context context, String name) {
    try {
      InputStream inputStream = context.getAssets().open(name);

      BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
      ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
      int streamLen;
      byte[] buffer = new byte[1024];//
      while ((streamLen = bufferedInputStream.read(buffer)) != -1) {
        byteArrayOutputStream.write(buffer, 0, streamLen);
      }
      byte[] bytes = byteArrayOutputStream.toByteArray();
      //byteArrayOutputStream.close();

      //byte[] bytes = toByteArrayUsingJava(inputStream);

      //byte[] bytes = getImageJpgFileByteDatas(inputStream);
      final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/*");
      RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JPG, bytes);
      return requestBody;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  public static byte[] toByteArrayUsingJava(InputStream is) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int reads = is.read();
    while (reads != -1) {
      baos.write(reads);
      reads = is.read();
    }
    return baos.toByteArray();
  }

  private static final byte[] getImageJpgFileByteDatas(InputStream inputStream1) throws IOException {

    BufferedInputStream inputStream = new BufferedInputStream(inputStream1);

    int len = inputStream.available();

    byte[] bytes = new byte[len];

    int readLen = inputStream.read(bytes);

    if (len != readLen) {

      bytes = null;

      inputStream.close();

      throw new IOException("read imge file is error");
    }

    inputStream.close();

    return bytes;
  }
}
